"""
Request Logger Middleware
=========================

Middleware for logging HTTP requests and responses.
Provides detailed logging for debugging and monitoring.
"""

import time
import logging
from flask import request, g
from datetime import datetime

# Initialize logger
logger = logging.getLogger(__name__)

class RequestLogger:
    """
    Middleware for logging HTTP requests and responses.
    
    Logs:
    - Request method and path
    - Request headers (excluding sensitive data)
    - Request body (for debugging)
    - Response status and duration
    - User information (if authenticated)
    """
    
    def __init__(self, app=None):
        """Initialize request logger middleware."""
        self.app = app
        if app:
            self.init_app(app)
    
    def init_app(self, app):
        """Initialize middleware with Flask app."""
        app.before_request(self.before_request)
        app.after_request(self.after_request)
    
    def before_request(self):
        """Log request details before processing."""
        g.start_time = time.time()
        g.request_id = self._generate_request_id()
        
        # Log basic request info
        logger.info(
            f"Request started - {request.method} {request.path}",
            extra={
                'request_id': g.request_id,
                'method': request.method,
                'path': request.path,
                'remote_addr': request.remote_addr,
                'user_agent': request.headers.get('User-Agent', 'Unknown'),
                'timestamp': datetime.utcnow().isoformat()
            }
        )
        
        # Log headers (excluding sensitive ones)
        headers_to_log = {
            k: v for k, v in request.headers.items()
            if k.lower() not in ['authorization', 'cookie', 'x-api-key']
        }
        
        if headers_to_log:
            logger.debug(
                f"Request headers: {headers_to_log}",
                extra={'request_id': g.request_id}
            )
        
        # Log request body for debugging (excluding sensitive endpoints)
        if request.method in ['POST', 'PUT', 'PATCH']:
            if not any(sensitive in request.path for sensitive in ['/auth/login', '/auth/register']):
                try:
                    body = request.get_json(silent=True)
                    if body:
                        logger.debug(
                            f"Request body: {body}",
                            extra={'request_id': g.request_id}
                        )
                except Exception:
                    pass
    
    def after_request(self, response):
        """Log response details after processing."""
        duration = time.time() - g.start_time if hasattr(g, 'start_time') else 0
        
        # Log response info
        logger.info(
            f"Request completed - {request.method} {request.path} - {response.status_code}",
            extra={
                'request_id': getattr(g, 'request_id', 'unknown'),
                'method': request.method,
                'path': request.path,
                'status_code': response.status_code,
                'duration_ms': round(duration * 1000, 2),
                'content_length': response.content_length,
                'timestamp': datetime.utcnow().isoformat()
            }
        )
        
        # Log slow requests
        if duration > 1.0:  # Requests taking more than 1 second
            logger.warning(
                f"Slow request detected - {request.method} {request.path} took {duration:.2f}s",
                extra={
                    'request_id': getattr(g, 'request_id', 'unknown'),
                    'duration': duration,
                    'status_code': response.status_code
                }
            )
        
        return response
    
    def _generate_request_id(self):
        """Generate unique request ID."""
        import uuid
        return str(uuid.uuid4())[:8]